<?php 

/**
 * @version $Id$
 * @create 2013-8-6 10:20:09 By xjiujiu
 * @description HongJuZi Framework
 * @copyRight Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */
defined('_HEXEC') or die('Restricted access!');
HClass::import('config.popo.articlepopo, app.cms.action.cmsaction, model.articlemodel');
class IndexAction extends CmsAction
{
    private $_adv;
    public function __construct()
    {
        parent::__construct();
        $this->_adv = HClass::quickLoadModel('adv');
		$this->_model = HClass::quickLoadModel('goods');
        $this->_popo  = $this->_model->getPopo();
        $this->_popo->setFieldAttribute('kuan', 'is_show', true);
        $this->_popo->setFieldAttribute('zhai', 'is_show', true);
        $this->_popo->setFieldAttribute('height', 'is_show', true);
        $this->_popo->setFieldAttribute('length', 'is_show', true);
        $this->_popo->setFieldAttribute('extend', 'is_show', true);
    }

    public function index()
    {
        $this->_assingAdvList();
        $this->_assignRecList();
        $this->_render('index');
    }

    private function _assingAdvList()
    {
        $list = $this->_adv->getAllRows('`is_show` = 1');
        HResponse::setAttribute('adv_list', $list);
    }
	
	 private function _assignCurGoodsList()
    {
        $parentId = HRequest::getParameter('parent_id') ?: 0;
        $list = $this->_goodsCategory->getAllRowsByFields('`id`,`name`,`image_path`',
            '`status` = 2 AND `parent_id` =' . $parentId);
        HResponse::setAttribute('sonlist', $list);
    }

    private function _assignCurClassList()
    {
        $record = $this->_goodsCategory->getRecordById(HRequest::getParameter('parent_id') ?: 821);

        $list = $this->_goodsCategory->getAllRowsByFields('`id`,`name`,`image_path`',
            '`status` = 2 AND `parent_id` =' . $record['parent_id']);

        HResponse::setAttribute('fatherlist', $list);
    }

    public function search()
    {
        $this->_search();
        $this->_render('select');
    }

    private function _search() {
        $this->_assignCurGoodsList();
        $this->_assignCurClassList();
        $this->_assignCurCateInfo();
        $this->_assignRecList();
        $this->_assignColorList();
        $this->_assignRimList();
        $this->_assignShapeList();
        $this->_assignMaterialList();
        $this->_assignModelList($this->_getWhere(), 24);
        $this->_formateGoodsList();
    }

    private function _formateGoodsList() {
        $likes   = $_COOKIE['Cart'];
        $likeArr = explode(',', $likes);
        $list    = HResponse::getAttribute('list');
        $colorMap = HArray::turnItemValueAsKey(HResponse::getAttribute('color_list'), 'id');
        foreach ($list as &$item) {
            $item['is_like'] = in_array($item['id'], $likeArr);
            $temp            = json_decode(HString::decodeHtml($item['extend']), true);
            foreach ($temp as &$val) {
                $val['content']    = $colorMap[$val['id']]['content'];
                $val['cimage_path'] = $colorMap[$val['id']]['image_path'];
            }
            $item['colors']  = $temp;
        }
        HResponse::setAttribute('list', $list);
    }

    private function _getWhere()
    {
        $parentId = I('parent_id');
        $keyword  = I('keyword');
        $colorId  = I('color_id');
        $color    = I('color');
        $rim      = I('rim');
        $shape    = I('shape');
        $meterial = I('meterial');
        $isShow   = I('is_show');
        $where    = '`status` = 2';
        if ($keyword) {
            if($keyword == 'procollect')
            {
                $where.= ' AND ' . HSqlHelper::whereIn('id', explode(',', $_COOKIE['Cart']));
            }
            else
            {
                $where .= ' AND `name` LIKE \'%' . $keyword . '%\'' ;
            }
        }
        if ($parentId) {
            $where .= ' AND `parent_id` = ' . $parentId ;
        }
        if ($colorId) {
            $where .= ' AND `color_id` LIKE \'%' . $colorId . ',%\'';
        }
        if ($color) {
            $color   = rtrim($color,","); 
            $color   = explode(',', $color);
            $where  .= ' AND (';
            foreach ($color as $key => $item) {
                if (count($color) - 1 > $key) {
                    $where .= '`color_id` LIKE \'%' . $item . ',%\' OR ';
                } else {
                    $where .= '`color_id` LIKE \'%' . $item . ',%\'';
                }
            }
            $where .= ' )';
        }
        if ($rim) {
            $where .= ' AND ' . HSqlHelper::whereIn('rim', array_filter(explode(',', $rim)));
        }
        if ($shape) {
            $where .= ' AND ' . HSqlHelper::whereIn('shape', array_filter(explode(',', $shape)));
        }
        if ($meterial) {
            $where .= ' AND ' . HSqlHelper::whereIn('meterial', array_filter(explode(',', $meterial)));
        }
        if ($isShow == 2) {
            $where .= ' AND `is_show` = 2';
        }
        return $where;
    }

    private function _assignCurCateInfo()
    {
        $record = $this->_goodsCategory->getRecordById(HRequest::getParameter('parent_id') ?: 0);
        HResponse::setAttribute('curParentTitle', $record['name']);
    }

    public function detail()
    {
        $id     = I('id');
        $record = $this->_model->getRecordById($id);
        $good_classname = $this->_goodsCategory->getRecordById( $record['parent_id']);
        $record['class_name']=strtoupper(substr($good_classname['name'],0,strrpos($good_classname['name']," ")));;
        $record['images'] = json_decode(HString::decodeHtml($record['extend']), true);
        array_multisort(array_column($record['images'],'brand'),SORT_ASC,$record['images'] );
        HResponse::json(array('rs' => true, 'data' => $record));
    }

    public function collect() {
        $this->_assignParentImagePath();
        $where = HSqlHelper::whereIn('id', explode(',', $_COOKIE['Cart']));
        $this->_assignModelList($where);
        $this->_render('collection');
    }

    private function _assignParentImagePath()
    {
        $articleCate = HClass::quickLoadModel('articlecat');
        $record     = $articleCate->getRecordByIdentifier('goods/collect');
        HResponse::setAttribute('bannerImage', HResponse::touri($record['image_path']));
    }

    public function export() {
        $id = I('id');
        ob_clean();
        $information = HClass::quickLoadModel('information');
        $goodsInfo  = $this->_model->getRecordById($id);
        $information = $information->getRecordByWhere('1 = 1');
        $this->_doExport($goodsInfo, $information);
    }

    private function _doExport($goodsInfo, $information) {
        HClass::import('vendor.TCPDF.examples.tcpdf_include', false);
        // create new PDF document
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        // set document information
        $pdf->SetCreator($goodsInfo['name']);
        $pdf->SetAuthor($goodsInfo['name']);
        $pdf->SetTitle($goodsInfo['name']);
        $pdf->SetSubject($goodsInfo['name']);
        $pdf->SetKeywords($goodsInfo['name']);
        $pdf->SetFont('stsongstdlight', '', 18); //设置中文显示

        // set default header data
        $pdf->SetHeaderData(ROOT_DIR . $information['image_path'], PDF_HEADER_LOGO_WIDTH, $goodsInfo['name'] . ' Images export', $goodsInfo['name']);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        $pdf->AddPage();

        $pdf->setJPEGQuality(75);
        $html="<table style=' background-color: #fff'><tr><td style='width:800px;' colspan=\"4\"><img  class=\"main-image\" src=\"". $goodsInfo['image_path']."\" width=\"800px\" /></td>" ;
        $html .= " <td style='width:100px;'><div style=\"float:right;width:100px;\"><h3 class=\"paraTitle\">".$goodsInfo['name']." </h3>";
        $html .= " <li class=\"onesharp\"> <img src=\"/static/template/cms/kirka/images/shape01.jpg\">".  $goodsInfo['kuan']."</li>";
        $html .= " <li class=\"towsharp\"><img src=\"/static/template/cms/kirka/images/shape02.jpg\">".  $goodsInfo['zhai']."</li>";
        $html .= " <li class=\"shrsharp\"><img src=\"/static/template/cms/kirka/images/shape03.jpg\">".  $goodsInfo['height'] ."</li>";
        $html .= "<li class=\"foursharp\"><img src=\"/static/template/cms/kirka/images/shape04.jpg\">".  $goodsInfo['length'] ."</li>";
        $html .="</div></td></tr>";
        $html .="<div style='width: 100%; height: 1px; background-color: #fff;'></div>";
        $html .="<tr><td colspan=\"5\"><table>";
        $images = json_decode(HString::decodeHtml($goodsInfo['extend']), true);
        foreach ($images as $ss=> $item) {
              if($ss==0)
              {
                  $html .= "<tr><td style=\"text-align:center; font-size: 18px;\"><img src=\"" .$item['image_path']."\" title=\"".$item['brand']."\" width=\"300\" >".$item['brand']."</td>";
              }
            elseif($ss==1)
            {
                $html .= "<td style=\"text-align:center; font-size: 18px;\"><img src=\"" .$item['image_path']."\" title=\"".$item['brand']."\" width=\"300\" >".$item['brand']."</td></tr>";
            }elseif($ss==2)
              {
                  $html .= "<tr><td style=\"text-align:center; font-size: 18px;\"><img src=\"" .$item['image_path']."\" title=\"".$item['brand']."\" width=\"300\" >".$item['brand']."</td><td></td></tr>";
              }
        }
        $html .=" </table></td></tr></table>";
        // 转化HTML页面
        $pdf->writeHTML($html);
        $pdf->Output($goodsInfo['name'] . '.pdf', 'I');
    }

    public function info() {
        $this->_search();
        $this->_render('common/goods2-item');
    }

    public function postemail()
    {
        $email = HVerify::isEmail(I('email'));
        $data = array(
            'name'     => $email,
            'user_name'=> 'username',
            'contact'  => 'no data',
            'content'  => 'no data',
            'parent_id'=> 0,
            'result'   => 'no data',
            'hash'     => 'no data'
        );
        $emailQueue = HClass::quickLoadModel('emailqueue');
        $record = $emailQueue->getRecordByWhere('`name` = \'' . $email . '\'');
        if (!$record) {
            $emailQueue->add($data);
        }
        HResponse::info('submit success');
    }
}